package vn.ikame.android.boojtran.truyenbua;

import java.util.ArrayList;
import java.util.Random;

import vn.ikame.android.boojtran.truyenbua.download.ItemListDowloadListener;
import vn.ikame.android.boojtran.truyenbua.download.ItemListDownload;
import vn.ikame.android.boojtran.truyenbua.object.GA;
import vn.ikame.android.boojtran.truyenbua.object.Item;
import vn.ikame.android.boojtran.truyenbua.utility.CConstant;
import vn.ikame.android.boojtran.truyenbua.utility.CStore;
import vn.ikame.android.boojtran.truyenbua.utility.ItemManager;
import vn.ikame.android.plugin.BaseActivity;
import vn.ikame.android.plugin.ChatActivity;
import vn.ikame.android.plugin.CustomDialog;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.image.SmartImageView;

public class SuperActivity extends BaseActivity implements
		ItemListDowloadListener {
	public static final String APP_NAME = "TruyenBua_Android";
	public static CStore store;
	public static int totalItem = 0;
	public static int previousTotal = 0;
	public static int visibleThreshold = 5;
	public static int itemCount = 30;
	public static boolean loading = true;
	public static ArrayList<Integer> showedArr = new ArrayList<Integer>();
	public static ArrayList<Integer> storyArr = new ArrayList<Integer>();
	private ProgressDialog progressDialog;
	private Toast toast;
	public static boolean isShowWifiWarning = false;
	public static int viewed = 0;
	public static ArrayList<Item> funStories = new ArrayList<Item>();
	protected boolean gotoBookmark = false;

	public void showProgress(String msg) {
		if (msg == null)
			return;
		try {
			dismissProgress();
			progressDialog = new ProgressDialog(SuperActivity.this);
			progressDialog.setMessage(msg);
			progressDialog.setCancelable(false);
			progressDialog.show();
		} catch (Exception e) {
		}
	}

	public void showMessage(String msg) {
		try {
			toast.cancel();
		} catch (Exception e) {
			e.printStackTrace();
		}
		toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
		toast.show();
	}

	public void dismissProgress() {
		try {
			if (progressDialog != null) {
				progressDialog.dismiss();
				progressDialog = null;
			}
		} catch (Exception e) {
		}
	}

	public void showInfoDialog(String title, String content) {
		CustomDialog.Builder infoDialog = new CustomDialog.Builder(
				SuperActivity.this);
		infoDialog.setTitle(title);
		infoDialog.setMessage(content);
		infoDialog.setPositiveButton("OK",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.dismiss();
					}
				});

		infoDialog.setCancelable(true);
		infoDialog.show();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	public boolean isBelongIntArray(ArrayList<Integer> arr, int one) {
		for (int object : arr) {
			if (one == object) {
				return true;
			}
		}
		return false;
	}

	public int getArrIndex(ArrayList<Item> arr, int one) {
		for (int i = 0; i < arr.size(); i++) {
			if (arr.get(i).getId() == one) {
				return i;
			}
		}
		return -1;
	}

	public boolean isOnline() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = cm.getActiveNetworkInfo();
		if (netInfo != null && netInfo.isConnected()) {
			return true;
		}
		return false;
	}

	public boolean isWifiConnected() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		// NetworkInfo netInfo = cm.getActiveNetworkInfo();
		State wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
				.getState();
		if (wifi == NetworkInfo.State.CONNECTED
				|| wifi == NetworkInfo.State.CONNECTING) {
			return true;
		}
		return false;
	}

	public void showNetworkDialog() {
		CustomDialog.Builder alert = new CustomDialog.Builder(this);
		alert.setTitle("Không có kết nối mạng");
		alert.setMessage("Phần mềm cần có kết nối mạng để cập nhật thông tin. Bạn có muốn kết nối mạng?");
		alert.setPositiveButton("Có", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				dialog.dismiss();
				startActivity(new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK));
			}
		});

		alert.setNegativeButton("Không", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				dialog.dismiss();
				startActivity(new Intent(SuperActivity.this, Exit.class));
			}
		});
		alert.setCancelable(false);
		alert.show();
	}

	public void showAboutDialog() {
		CustomDialog.Builder alert = new CustomDialog.Builder(this);
		alert.setMessage(getResources().getString(R.string.about));
		alert.setPositiveButton("Gửi mail",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						final Intent emailIntent = new Intent(
								android.content.Intent.ACTION_SEND);

						/* Fill it with Data */
						emailIntent.setType("plain/text");
						emailIntent.putExtra(
								android.content.Intent.EXTRA_EMAIL,
								new String[] { "support@ikame.vn" });
						emailIntent.putExtra(
								android.content.Intent.EXTRA_SUBJECT,
								"Ứng dụng Truyện bựa 18+");
						emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
								"Nội dung: ");

						/* Send it off to the Activity-Chooser */
						startActivity(Intent.createChooser(emailIntent,
								"Send mail..."));
					}
				});

		alert.setNegativeButton("Đóng", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				dialog.dismiss();
			}
		});

		alert.setCancelable(false);
		alert.show();
	}

	protected void exitApp() {
		ItemManager.getInstance().clearImageCache();
		startActivity(new Intent(SuperActivity.this, Exit.class));
		SuperActivity.this.finish();
	}

	protected void showMessageDialog(String mess) {
		CustomDialog.Builder alert = new CustomDialog.Builder(this);
		alert.setTitle("Thông báo");
		alert.setMessage(mess);
		alert.setPositiveButton("Đóng", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				dialog.dismiss();
			}
		});
		alert.setCancelable(true);
		alert.show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.option_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.chat:
			startActivity(new Intent(SuperActivity.this, ChatActivity.class));
			break;
		case R.id.moregame:
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setData(Uri.parse("market://search?q=ikame"));
			startActivity(intent);
			break;
		case R.id.rateapp:
			Intent intent1 = new Intent(Intent.ACTION_VIEW);
			intent1.setData(Uri.parse("market://details?id=" + APP_PACKAGE));
			startActivity(intent1);
			break;
		case R.id.share:
			Intent sharingIntent = new Intent(Intent.ACTION_SEND);
			sharingIntent.setType("text/plain");
			sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT,
					"https://play.google.com/store/apps/details?id="
							+ APP_PACKAGE);
			sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
					"Ứng dụng Truyện Bựa 18+");
			startActivity(Intent.createChooser(sharingIntent, "Share using"));

			break;
		case R.id.funstory:
			if (funStories == null || funStories.size() <= 0) {
				requestListItems(CConstant.SVR_FUNSTORY_LINK, storyArr.size(),
						itemCount);
			} else {
				startActivity(new Intent(SuperActivity.this, FunStory.class));
			}
			break;
		case R.id.bookmark:
			if (store.getPic() > -1) {
				int pic = getArrIndex(ItemManager.getInstance().getListItem(),
						store.getPic());
				if (pic != -1) {
					ItemManager.getInstance().setCurItem(pic);
					if (!isBelongIntArray(showedArr, ItemManager.getInstance()
							.getItem(pic).getId())) {
						showedArr.add(ItemManager.getInstance().getItem(pic)
								.getId());
						store.setShowedArr(showedArr);
					}
					startActivity(new Intent(SuperActivity.this, Viewer.class));
				} else {
					requestListItems(CConstant.SVR_IMG_LINK, 0, ItemManager
							.getInstance().getItem(0).getId()
							- store.getPic() + 10);
					gotoBookmark = true;
				}
			} else {
				Toast.makeText(this, "Bạn chưa xem truyện nào!",
						Toast.LENGTH_SHORT).show();
			}
			break;
		case R.id.refresh:
			requestListItems(CConstant.SVR_IMG_LINK, 0,
					(previousTotal > 0 ? previousTotal : itemCount));
			break;
		case R.id.about:
			showAboutDialog();
			break;

		}
		return true;
	}

	public void createNotificationAlert() {
		if (noti.isShow()) {
			return;
		}

		try {
			System.out.println("Show Notify");
			noti.setShow(true);
			noti.setAlert(new CustomDialog.Builder(this));
			noti.getAlert().setMessage(noti.getContent());

			SmartImageView image = (SmartImageView) noti.getAlert().getView()
					.findViewById(R.id.icon);
			image.setImageUrl(noti.getIconLink());

			TextView text = (TextView) noti.getAlert().getView()
					.findViewById(R.id.name);
			text.setText(noti.getName());

			if (!noti.getAppLink().equals("")) {
				noti.getAlert().setPositiveButton("Xem app",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								dialog.dismiss();
								Intent intent = new Intent(Intent.ACTION_VIEW);
								intent.setData(Uri.parse(noti.getAppLink()));
								startActivity(intent);
							}
						});
			}

			noti.getAlert().setNegativeButton("Thoát",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							dialog.dismiss();
							finish();
							System.gc();
							android.os.Process.killProcess(android.os.Process
									.myPid());
						}
					});
			noti.getAlert().setCancelable(true);
			noti.getAlert().show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void requestListItems(String svr_link, int start, int count) {
		Log.e("TAG", svr_link);
		if (isOnline()) {
			ItemListDownload itemListDownload = new ItemListDownload(this, this);
			itemListDownload.start(svr_link, start, count);
		} else {
			showNetworkDialog();
		}
	}

	protected void showReconnectDialog(final String svr_link, final int start,
			final int count) {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle("Không thể kết nối tới server");
		alert.setMessage("Thử lại?");
		alert.setPositiveButton("Thử lại",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.dismiss();
						requestListItems(svr_link, start, count);
					}
				});

		alert.setNegativeButton("Thoát", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				dialog.dismiss();
				startActivity(new Intent(SuperActivity.this, Exit.class));
			}
		});
		alert.setCancelable(true);
		alert.show();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK
				|| keyCode == KeyEvent.KEYCODE_HOME) {
			return false;
		}
		return false;
	}

	@Override
	public void onDownloadFinish(ArrayList<Item> result, String svr_link,
			int start, int count) {
		if (result != null && result.size() > 0) {
			Log.e("TAG", "ok:" + result.size());
			if (svr_link.equals(CConstant.SVR_IMG_LINK)) {
				ItemManager.getInstance().setListItem(result);
				if (gotoBookmark) {
					gotoBookmark = false;
					int pic = getArrIndex(ItemManager.getInstance()
							.getListItem(), store.getPic());
					if (pic != -1) {
						ItemManager.getInstance().setCurItem(pic);
						if (!isBelongIntArray(showedArr, ItemManager
								.getInstance().getItem(pic).getId())) {
							showedArr.add(ItemManager.getInstance()
									.getItem(pic).getId());
							store.setShowedArr(showedArr);
						}
						startActivity(new Intent(SuperActivity.this,
								Viewer.class));
					}
				} else {
					startActivity(new Intent(SuperActivity.this, ListItem.class));
					finish();
				}
			} else if (svr_link.equals(CConstant.SVR_FUNSTORY_LINK)) {
				Log.e("TAG", "vkl");
				funStories = result;
				startActivity(new Intent(SuperActivity.this, FunStory.class));
			}
		} else {
			if (svr_link.equals(CConstant.SVR_IMG_LINK)) {
				GA.trackDetailView(APP_NAME + "_downloadListError");
			} else if (svr_link.equals(CConstant.SVR_FUNSTORY_LINK)) {
				if (result.size() <= 0) {
					storyArr.clear();
					store.setStoryArr(storyArr);
					if (funStories == null || funStories.size() <= 0) {
						requestListItems(CConstant.SVR_FUNSTORY_LINK, 0,
								itemCount);
					} else {
						startActivity(new Intent(SuperActivity.this,
								FunStory.class));
					}
				} else {
					GA.trackDetailView(APP_NAME + "_funStoryDownloadListError");
					showReconnectDialog(svr_link, start, count);
					Log.e("TAG", "lose2");
				}
			}
			showReconnectDialog(svr_link, start, count);
			Log.e("TAG", "lose");
		}
	}

	@Override
	public void onDownloadError(String svr_link, int start, int count) {
		if (svr_link.equals(CConstant.SVR_IMG_LINK)) {
			GA.trackDetailView(APP_NAME + "_downloadListError");
		} else if (svr_link.equals(CConstant.SVR_FUNSTORY_LINK)) {
			GA.trackDetailView(APP_NAME + "_funStoryDownloadListError");
		}
		showReconnectDialog(svr_link, start, count);
	}

	public int rand(int min, int max) {
		Random randInt = new Random();
		int b = min - 1;
		while (b < min) {
			b = randInt.nextInt(max);
		}
		return b;
	}
}